import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Global } from '../../common/global';
import { BusiProvider } from '../../providers/busi/busi';
import { NativeProvider } from '../../providers/native/native';

/**
 * Generated class for the UserimageeditPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-userimageedit',
  templateUrl: 'userimageedit.html',
})
export class UserimageeditPage {
  imgurl:any;
  imgpath: any;
  serverimgpath:any;
  constructor(public navCtrl: NavController, public navParams: NavParams,private camera: Camera,
     private transfer: FileTransfer, private file: File,private busi:BusiProvider,private native:NativeProvider) {
    this.imgurl = this.navParams.get("imgurl");
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad UserimageeditPage');
  }
  changeimage(){
    this.getPic();
  }

  getPic() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum:false
    }

    this.camera.getPicture(options).then((imageData) => {
      this.imgpath = imageData;
      this.imgUpload();
    }, (err) => {

    });
  }
  imgUpload() {
    const fileTransfer: FileTransferObject = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: 'name.jpg',
      headers: {},
    };
    const serverAddress = localStorage.getItem("serverAddress");
    fileTransfer.upload(this.imgpath, Global.base_url+"upload/fileupload", options)
      .then((data) => {
        this.imgurl =serverAddress+ JSON.parse(data.response).result.filepath;
        this.serverimgpath = this.imgpath;
      }, (err) => {
        console.log(err);
      });
  }
  save(){
    this.busi.updateimg(this.imgurl).subscribe(
      data=>{
        this.native.showToast("修改头像成功");
        this.navCtrl.pop();
      },error=>{

      }
    );
  }

}
